<template>
  <div class="action-configuration-wrapper">
    <div class="action-configuration-header">
      <el-text style="margin: 0 15px">表单名称:</el-text>
      <el-input style="width: 200px" disabled :value="formDefinition.showName"/>

      <el-text style="margin: 0 15px">视图名称:</el-text>
      <el-select v-model="selectdViewId" @change="viewChange" placeholder="请选择视图">
        <el-option
            v-for="item in formDefinition.views"
            :key="item.id"
            :label="item.viewName"
            :value="item.id"/>
      </el-select>
    </div>
    <div class="action-configuration-button-wrapper">
      <el-button round type="primary" icon="plus" @click="addNewViewAction">新建</el-button>
      <el-button round icon="document" @click="copyViewAction">复制</el-button>
      <el-button round type="warning" icon="delete" @click="removeActions">删除</el-button>
    </div>
    <div class="action-configuration-button-body">
      <div class="action-configuration-button-left">
        <el-table :data="viewActions" height="100%" @row-click="viewActionRowClick"
                  @selectionChange="viewActionSelectionChange" ref="viewActionsTable"
                  stripe border style="width: 100%">操作设置
          <el-table-column type="selection" width="55"/>

          <el-table-column prop="actionName" label="操作权限名称" width="180">
          </el-table-column>
          <el-table-column prop="system" label="是否系统预制">
            <template #default="{row}">
              <span>{{ row.systemPreset === '1' ? '是' : '否' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="actionType" label="系统预制类别">
            <template #default="scope">
              <span>{{ getActionType(scope.row.actionType) }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="action-configuration-button-padding"></div>
      <div class="action-configuration-button-right">
        <div class="action-configuration-button-form-wrapper">
          <el-form style="min-width: 1000px" inline ref="actionForm"
                   label-width="80px" :model="viewActionData">
            <el-form-item prop="actionName" label="名称" :rules="[]">
              <el-input placeholder="请输入操作权限名称" v-model="viewActionData.actionName"/>
            </el-form-item>

            <el-form-item prop="actionName" label="操作类型" :rules="[]">
              <el-select v-model="viewActionData.actionType" placeholder="请选择操作类型"
                         :disabled="viewActionData.systemPreset === '1'">
                <el-option v-for="item in actionType" :label="item.title"
                           :value="item.value" :key="item.value"/>
              </el-select>
            </el-form-item>

            <el-form-item prop="actionName" label="视图" :rules="[]">
              <el-select v-model="viewActionData.viewId" placeholder="选择视图"
                         style="width: 100%" @change="viewActionDataViewChange"
                         :disabled="viewActionData.systemPreset === '1'">
                <el-option
                    v-for="view in formDefinition.views"
                    :key="view.id" :label="view.viewName"
                    :value="view.id"/>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button round icon="edit" :disabled="isEmpty(viewActionData.id)"
                         @click="openSubFormButtonActionConfiguration">明细行操作</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="action-configuration-button-table-wrapper">
          <el-table :data="fieldActions" height="100%" style="width: 100%" stripe>
            <el-table-column prop="fieldShowName" min-width="180" label="数据域" show-overflow-tooltip/>
            <el-table-column prop="authBrowse" label="浏览">
              <template #header>
                <el-tag @click="allAuthSet('browse')" round hit
                        class="action-configuration-button-table-header-tag">浏览
                </el-tag>
              </template>
              <template #default="scope">
                <div>
                  <el-radio-group v-model="scope.row.defaultAuth"
                                  @change="() => authChange(scope.row)">
                    <el-radio model-value="browse" label="browse">
                      <span/>
                    </el-radio>
                  </el-radio-group>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="authEdit" label="编辑">
              <template #header>
                <el-tag @click="allAuthSet('edit')" round hit
                        class="action-configuration-button-table-header-tag">编辑
                </el-tag>
              </template>
              <template #default="scope">
                <el-radio-group v-model="scope.row.defaultAuth"
                                @change="() => authChange(scope.row)">
                  <el-radio model-value="edit" label="edit">
                    <span/>
                  </el-radio>
                </el-radio-group>
              </template>
            </el-table-column>
            <el-table-column prop="authHide" label="隐藏">
              <template #header>
                <el-tag @click="allAuthSet('hide')" round hit
                        class="action-configuration-button-table-header-tag">隐藏
                </el-tag>
              </template>
              <template #default="scope">
                <el-radio-group v-model="scope.row.defaultAuth"
                                @change="() => authChange(scope.row)">
                  <el-radio model-value="hide" label="hide">
                    <span/>
                  </el-radio>
                </el-radio-group>
              </template>
            </el-table-column>
            <el-table-column prop="NotNull" label="必填">
              <template #header>
                <el-tag @click="allNotNullToggle" round hit
                        class="action-configuration-button-table-header-tag">必填
                </el-tag>
              </template>
              <template #default="scope">
                <el-checkbox v-model="scope.row.defaultNotNull"
                             :disabled="scope.row.defaultAuth !== 'edit'"
                             true-label="1" false-label="0"/>
              </template>
            </el-table-column>

            <el-table-column prop="defaultValue" label="初始值设置" width="180">
              <template #default="{row}">
                <el-input placeholder="请设置初始值" readonly
                          @click="() => createDefaultValue(row)" v-model="row.defaultValueText"/>
              </template>
            </el-table-column>
            <el-table-column prop="formulas" label="条件" >
              <template #default="{row}">
                <el-tag style="cursor: pointer" @click="() => configFormulas(row)"
                        :type="isEmpty(row.actionFormulas) ? 'info' : '' ">条件</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <FModal ref="newViewActionFModal" @ok="doAddNewViewAction"
            header="编辑" width="620">
      <el-form ref="newViewActionForm" label-width="120px" style="padding-right: 80px"
               :model="newViewAction">
        <el-form-item prop="actionName" label="操作权限名称" :rules="[required]">
          <el-input placeholder="请输入权限名称"
                    v-model="newViewAction.actionName"/>
        </el-form-item>

        <el-form-item prop="actionName" label="操作类型" :rules="[required]">
          <el-select placeholder="请选择操作类型"
                     v-model="newViewAction.actionType" style="width: 100%">
            <el-option v-for="item in actionType" :label="item.title"
                       :value="item.value" :key="item.value"/>
          </el-select>
        </el-form-item>

        <el-form-item prop="actionName" label="视图" :rules="[required]">
          <el-select v-model="newViewAction.viewIds" multiple
                     collapse-tags collapse-tags-tooltip placeholder="选择视图"
                     style="width: 100%">
            <el-option
                v-for="view in formDefinition.views"
                :key="view.id" :label="view.viewName"
                :value="view.id"/>
          </el-select>
        </el-form-item>
      </el-form>
    </FModal>

    <DefaultValueCreateModal ref="DefaultValueCreateModal"/>
    <DefaultValueFormulaModal ref="DefaultValueFormulaModal"/>
    <SubFormButtonActionConfiguration ref="SubFormButtonActionConfiguration"/>
  </div>
</template>

<script>
import {DefaultFormDefinition, DefaultViewAction} from '@/components/form/DefaultFormDefinition';
import './style.css';
import {guid, isEmpty, isNotEmpty, required} from '@/utils/CommonUtils';
import FSection from '@/components/FSection/index.vue';
import ViewActonHelper from '@/components/form/FromDesigner/ViewActonHelper';
import InputComponents from '@/components/form/InputComponents';
import FModal from '@/components/FModal';
import {ElMessageBox} from 'element-plus';
import DefaultValueCreateModal from '@/components/form/ActionConfiguration/DefaultValueCreateModal';
import DefaultValueFormulaModal from '@/components/form/ActionConfiguration/DefaultValueFormulaModal';
import SubFormButtonActionConfiguration from '@/components/form/ActionConfiguration/SubFormButtonActionConfiguration.vue';


export default {
  name: "ActionConfiguration",
  components: {
    FSection,
    DefaultValueFormulaModal,
    SubFormButtonActionConfiguration,
    DefaultValueCreateModal,
    ...InputComponents,
    FModal
  },
  data() {
    return {
      newViewAction: {
        actionName: undefined,
        viewIds: [],
        actionType: undefined
      },
      required,
      formDefinition: DefaultFormDefinition,
      selectdViewId: undefined,
      viewActions: [],
      fieldActions: [],
      viewActionData: DefaultViewAction,
      actionType: [
        {title: '审批', value: 'approve'},
        {title: '填写', value: 'edit'},
        {title: '显示', value: 'show'},
      ]
    };
  },
  methods: {
    isEmpty,
    isNotEmpty,
    setData(formDefinition) {
      this.formDefinition = formDefinition;
      this.viewActonHelper = new ViewActonHelper(this.formDefinition);
      this.viewActonHelper.refreshViews();
      this.viewChange(this.formDefinition.views[0].id);
    },
    getActionType(actionType) {
      let type = this.actionType.find(s => s.value === actionType);
      return type?.title;
    },
    viewChange(selectdViewId) {
      this.selectdViewId = selectdViewId;
      this.getViewActions();
      this.fieldActions = [];
      this.$refs.viewActionsTable.clearSelection();
      this.viewActionData = JSON.parse(JSON.stringify(DefaultViewAction));
    },
    addNewViewAction() {
      this.$refs.newViewActionFModal.open();
      this.newViewAction = {
        actionName: undefined,
        viewIds: [],
        actionType: undefined
      };
    },
    allAuthSet(auth) {
      let fieldActions = this.fieldActions;
      if (isEmpty(fieldActions)) fieldActions = [];
      fieldActions.forEach(action => {
        action.defaultAuth = auth;
        if (auth !== 'edit') {
          action.defaultNotNull = '0';
        }
      });
      fieldActions.splice(0, 0);
    },
    openSubFormButtonActionConfiguration() {
      this.$refs.SubFormButtonActionConfiguration.setData(this.viewActionData, this.formDefinition);
    },
    allNotNullToggle() {
      let trueCount = 0, allCount = 0;
      let fieldActions = this.fieldActions;
      if (isEmpty(fieldActions)) fieldActions = [];
      fieldActions.forEach(a => {
        if (a.defaultAuth === 'edit') {
          allCount++;
        }
        if (a.defaultNotNull + '' === '1'
            && a.defaultAuth === 'edit') {
          trueCount++;
        }
      });

      if (trueCount === allCount) {
        fieldActions.forEach(a => {
          if (a.defaultAuth === 'edit') {
            a.defaultNotNull = '0';
          }
        });
      } else {
        fieldActions.forEach(a => {
          if (a.defaultAuth === 'edit') {
            a.defaultNotNull = '1';
          }
        });
      }
    },
    removeActions() {
      let rows = this.$refs.viewActionsTable.getSelectionRows();
      if (rows.length <= 0) {
        this.$message.warning('请选择需要删除的数据行');
        return;
      }
      let list = rows.filter(row => row.systemPreset + '' === '1');
      if (isNotEmpty(list)) {
        this.$message.warning('系统预置操作权限不能删除');
        return;
      }

      ElMessageBox.confirm('删除后不可恢复, 确定删除吗', '确定删除?', {
        draggable: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        list = this.formDefinition.viewActions.filter(viewAction => {
          let res = rows.find(row => row === viewAction);
          return isEmpty(res);
        });

        this.formDefinition.viewActions = list;
        this.viewChange(this.selectdViewId);
      }).catch(() => {

      });
    },
    copyViewAction() {
      let rows = this.$refs.viewActionsTable.getSelectionRows();
      if (rows.length <= 0) {
        this.$message.warning('请选择需要复制的数据行');
        return;
      }
      this.$refs.viewActionsTable.clearSelection();
      let tempList = JSON.parse(JSON.stringify(rows));
      tempList.forEach(t => {
        t.id = guid();
        t.actionName += '(副本)';
        t.systemPreset = '0';
      });
      this.formDefinition.viewActions.push(...tempList);

      this.viewChange(this.selectdViewId);
    },
    createDefaultValue(row) {
      let fieldDefinition = this.getFieldDefinition(row)
      this.$refs.DefaultValueCreateModal.setData(row, fieldDefinition);
    },
    getFieldDefinition(row) {
      if (row.formName === this.formDefinition.formName) {
        return this.formDefinition.fields.find(f => f.tableFieldName === row.formField);
      }
      let subForms = this.formDefinition.subForms
      for (let i = 0; i < subForms.length; i++) {
        let subForm = subForms[i];
        if (subForm.formName === row.formName) {
          return subForm.fields.find(f => f.tableFieldName === row.formField);
        }
      }
      return undefined
    },
    configFormulas(row) {
      this.$refs.DefaultValueFormulaModal.setData(row, this.formDefinition);
    },
    doAddNewViewAction() {
      this.$refs.newViewActionForm.validate((valid, errors) => {
        if (valid) {
          let viewIds = this.newViewAction.viewIds;
          viewIds.forEach(viewId => {
            let newAction = JSON.parse(JSON.stringify(DefaultViewAction));
            newAction.id = guid();
            newAction.viewId = viewId;
            newAction.actionName = this.newViewAction.actionName;
            newAction.actionType = this.newViewAction.actionType;
            newAction.actionKey = guid();

            this.formDefinition.viewActions.push(newAction);
            this.viewActonHelper.refreshViews();
            this.viewChange(this.selectdViewId);
          });

          this.$refs.newViewActionFModal.close();
        }
      });
    },
    viewActionDataViewChange() {
      this.viewChange(this.selectdViewId);
    },
    authChange(row) {
      if (row.defaultAuth !== 'edit') {
        row.defaultNotNull = '0';
      }
    },
    getViewActions() {
      let viewActions = this.formDefinition.viewActions.filter(v => v.viewId === this.selectdViewId);
      if (isEmpty(viewActions)) viewActions = [];
      this.viewActions = viewActions;
    },
    viewActionRowClick(row, column, event) {
      this.$refs.viewActionsTable.clearSelection();
      this.$refs.viewActionsTable.toggleRowSelection(row, true);
      this.viewActionSelectionChange([row]);
    },
    viewActionSelectionChange(data) {
      if (isNotEmpty(data)) {
        this.viewActionData = data[0];
        this.fieldActions = this.viewActionData.fieldActions;
      }
    },
  }
};
</script>
